// grid和布局的全局变量
Ext.grid.CheckColumn = function (config) {
    Ext.apply(this, config);
    if (!this.id) {
        this.id = Ext.id();
    }
    this.renderer = this.renderer.createDelegate(this);
};

Ext.grid.CheckColumn.prototype = {
    init: function (grid) {
        this.grid = grid;
        this.grid.on('render', function () {
            var view = this.grid.getView();
            view.mainBody.on('mousedown', this.onMouseDown, this);
        }, this);
    },
    onMouseDown: function (e, t) {
        if (t.id == this.id) {
            e.stopEvent();
            var v = this.grid.getView();
            var rowIndex = v.findRowIndex(t);
            var columnIndex = v.findCellIndex(t);
            var record = this.grid.store.getAt(rowIndex);
            var value = !record.data[this.dataIndex];
            record.set(this.dataIndex, value);
            this.grid.fireEvent('afteredit', this.grid, record, this.dataIndex,
                value, !value, rowIndex, rowIndex)
        }
    },
    renderer: function (v, p, record) {
        p.css += ' x-grid3-check-col-td';
        return '<div id="' + this.id + '" class="x-grid3-check-col'
            + (v ? '-on' : '') + '">&#160;</div>';
    }
};
var column_align_json = new Ext.data.SimpleStore({
    fields: ['value', 'name'],
    data: [['left', 'left'], ['center', 'center'], ['right', 'right']]
});
/*if  (!Ext.grid.GridView.prototype.templates) {
    Ext.grid.GridView.prototype.templates = {};    
}    
Ext.grid.GridView.prototype.templates.cell =  new  Ext.Template(    
     '<td class="x-grid3-col x-grid3-cell x-grid3-td-{id} x-selectable {css}" style="{style}" tabIndex="0" {cellAttr}>' ,    
     '<div class="x-grid3-cell-inner x-grid3-col-{id}" {attr}>{value}</div>' ,    
     '</td>'    
); */
var sm;
var cm;
var store;
var grid;
var viewport;
var Plant;
Ext.onReady(function () {
    Ext.QuickTips.init();
    var sm = new Ext.grid.CheckboxSelectionModel();
    var combo1 = new Ext.form.ComboBox({
        typeAhead: true,
        triggerAction: 'all',
        lazyRender: true,
        mode: 'local',
        store: new Ext.data.ArrayStore({
            id: 1,
            fields: [
                'myId',
                'displayText'
            ],
            data: [[true, '隐藏'], [false, '不隐藏']]
        }),
        valueField: 'myId',
        displayField: 'displayText'
    });
    var combo2 = new Ext.form.ComboBox({
        typeAhead: true,
        triggerAction: 'all',
        lazyRender: true,
        mode: 'local',
        store: new Ext.data.ArrayStore({
            id: 2,
            fields: [
                'myId',
                'displayText'
            ],
            data: [[true, '模糊查询'], [false, '不模糊查询']]
        }),
        valueField: 'myId',
        displayField: 'displayText'
    });
    var combo3 = new Ext.form.ComboBox({
        typeAhead: true,
        triggerAction: 'all',
        lazyRender: true,
        mode: 'local',
        store: new Ext.data.ArrayStore({
            id: 3,
            fields: [
                'myId',
                'displayText'
            ],
            data: [[true, '排序'], [false, '不排序']]
        }),
        valueField: 'myId',
        displayField: 'displayText'
    });
    var combo4 = new Ext.form.ComboBox({
        typeAhead: true,
        triggerAction: 'all',
        lazyRender: true,
        mode: 'local',
        store: new Ext.data.ArrayStore({
            id: 4,
            fields: [
                'myId',
                'displayText'
            ],
            data: [[false, '否'], [true, '是']]
        }),
        valueField: 'myId',
        displayField: 'displayText'
    });
    var combo5 = new Ext.form.ComboBox({
        typeAhead: true,
        triggerAction: 'all',
        lazyRender: true,
        mode: 'local',
        store: new Ext.data.ArrayStore({
            id: 4,
            fields: [
                'myId',
                'displayText'
            ],
            data: [['db', '数据库字段'], ['virtual', '虚拟字段']]
        }),
        valueField: 'myId',
        displayField: 'displayText'
    });
    var combo6 = new Ext.form.ComboBox({
        typeAhead: true,
        triggerAction: 'all',
        lazyRender: true,
        mode: 'local',
        store: new Ext.data.ArrayStore({
            id: 6,
            fields: [
                'myId',
                'displayText'
            ],
            data: [['0', '不合并'], ['2', '2行']]
        }),
        valueField: 'myId',
        displayField: 'displayText'
    });
    var combo7 = new Ext.form.ComboBox({
        typeAhead: true,
        triggerAction: 'all',
        lazyRender: true,
        mode: 'local',
        store: new Ext.data.ArrayStore({
            id: 7,
            fields: [
                'myId',
                'displayText'
            ],
            data: [['0', '不合并'], ['2', '2列'], ['3', '3列'], ['4', '4列'], ['5', '5列']]
        }),
        valueField: 'myId',
        displayField: 'displayText'
    });
    var combo8 = new Ext.form.ComboBox({
        typeAhead: true,
        triggerAction: 'all',
        lazyRender: true,
        mode: 'local',
        store: new Ext.data.ArrayStore({
            id: 8,
            fields: [
                'myId',
                'displayText'
            ],
            data: [['', '无'], ['start', '开始行符号'], ['end', '结束行符号']]
        }),
        valueField: 'myId',
        displayField: 'displayText'
    });
    cm = new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(), sm, {
        header: 'ID',
        dataIndex: 'id',
        hidden: true,
        width: 10
    }, {
        header: '表格字段',
        dataIndex: 'columnName',
        width: 100
    }, {
        header: '标题',
        dataIndex: 'title',
        editor: new Ext.form.TextField({
            allowBlank: false,
            blankText: "不允许为空"
        }),
        width: 120
    }, {
        header: '宽度',
        dataIndex: "width",
        menuDisabled: true,
        width: 55,
        editor: new Ext.form.NumberField({
            allowBlank: false,
            blankText: "不允许为空"
        })
    }, {
        //xtype : 'checkcolumn',
        header: '模糊查询',
        dataIndex: 'supportFuzzySearch',
        width: 55,
        editor: combo2,
        hidden: true,
        renderer: Ext.util.Format.comboRenderer(combo2)
    }, {
        //xtype : 'checkcolumn',
        header: '是否隐藏',
        dataIndex: 'hidden',
        width: 55,
        editor: combo1,
        renderer: Ext.util.Format.comboRenderer(combo1)
    }, {
        //xtype : 'checkcolumn',
        header: '是否排序',
        dataIndex: 'sortable',
        width: 55,
        editor: combo3,
        renderer: Ext.util.Format.comboRenderer(combo3)
    }, {
        header: '对齐数据',
        dataIndex: 'column_align',
        width: 80,
        editor: new Ext.form.ComboBox({
            hideLabel: true,
            lazyRender: true, // 值为true时阻止ComboBox渲染直到该对象被请求
            store: column_align_json,
            displayField: "name",
            valueField: "value",
            mode: "local",
            editable: false,
            triggerAction: "all"

        }),
    }, {
        //xtype : 'checkcolumn',
        header: '字段类型',
        dataIndex: 'column_type',
        width: 55,
        //editor: combo5,
        renderer: Ext.util.Format.comboRenderer(combo5)
    }, {
        header: '数据映射类型',
        dataIndex: 'ref_type',
        hidden: true,
        renderer: renderer_data,
        width: 170
    }, {
        header: '数据映射',
        dataIndex: 'ref_params',
        editor: new Ext.grid.GridEditor(new Ext.form.TextField()),
        width: 170
    }, {
        header: '格式化函数',
        dataIndex: 'formatter',
        width: 170,
        editor: new Ext.grid.GridEditor(new Ext.form.TextArea())
    }, {
        header: '唯一标识',
        dataIndex: 'pk',
        editor: combo4,
        renderer: Ext.util.Format.comboRenderer(combo4),
        width: 55
    }, {
        header: 'orderIndex',
        dataIndex: 'orderIndex',
        hidden: true,

        width: 80
    }, {
        header: '表头合并行',
        dataIndex: 'rowspan',
        editor: combo6,
        renderer: Ext.util.Format.comboRenderer(combo6),
        width: 55
    }, {
        header: '表头合并列',
        dataIndex: 'colspan',
        editor: combo7,
        renderer: Ext.util.Format.comboRenderer(combo7),
        width: 55
    }, {
        header: '表头行符号',
        dataIndex: 'row_symbol',
        editor: combo8,
        renderer: Ext.util.Format.comboRenderer(combo8),
        width: 55
    }]);
    Plant = Ext.data.Record.create([{
        name: 'id',
        type: 'string'
    }, {
        name: 'columnName',
        type: 'string'
    }, {
        name: 'title',
        type: 'string'
    }, {
        name: 'width',
        type: "int"
    }, {
        name: 'hotlinkName',
        type: "string"
    }, {
        name: 'hotlinkParam',
        type: "string"
    }, {
        name: 'supportFuzzySearch',
        type: 'bool'
    }, {
        name: 'hidden',
        type: 'bool'
    }, {
        name: 'pk',
        type: 'bool'
    }, {
        name: 'sortable',
        type: 'bool'
    }, {
        name: 'formatter',
        type: 'string'
    }, {
        name: 'column_align',
        type: 'string'
    }, {
        name: 'column_type',
        type: 'string'
    }, {
        name: 'dbColumnName',
        type: 'string'
    }, {
        name: 'ref_type',
        type: 'string'
    }, {
        name: 'ref_params',
        type: 'string'
    }, {
        name: 'orderIndex',
        type: "int"
    }, {
        name: 'rowspan',
        type: "int"
    }, {
        name: 'colspan',
        type: "int"
    }, {
        name: 'row_symbol',
        type: "string"
    }]);

    store = new Ext.data.Store({
        baseParams: {
            id: id
        },
        proxy: new Ext.data.HttpProxy({
            url: basePath
            + 'repository/worklist/columns/getWorkListColumnsJson'
        }),
        reader: new Ext.data.JsonReader({
            totalProperty: "total",
            root: "root",
            id: "id"
        }, ['id', 'columnName', 'title', 'width', 'supportFuzzySearch',
            'orderIndex', 'hotlinkParam', 'hidden', 'hotlinkName', 'pk',
            'sortable', 'formatter', 'column_align', 'column_type', 'dbColumnName', 'ref_params', 'ref_type','colspan','rowspan','row_symbol'], Plant)
    });
    grid = new Ext.grid.EditorGridPanel({
        renderTo: 'grid',
        store: store,
        region: 'center',
        cm: cm,
        sm: sm,
        trackMouseOver: false,
        clicksToEdit: 1,
        loadMask: {
            msg: '正在加载数据，请稍候...'
        },
        border: false,
        enableDragDrop: true,
        viewConfig: {
            forceFit: true
            /*templates: {      
                cell: new Ext.Template(    
                  '<td class="x-grid3-col x-grid3-cell x-grid3-td-{id}   x-selectable {css}" style="{style}"   tabIndex="0" {cellAttr}>',   
                  '<div class="x-grid3-cell-inner x-grid3-col-{id}"  {attr}>{value}</div>',  
                  '</td>'  
                   )  
                }*/
        },
        listeners: {
            'bodyscroll': function () {
                return false;
            }
        },
        tbar: [{
            text: '添加数据库字段',
            iconCls: 'iconNew',
            handler: function () {
                openWorkListMetadatMapWin();
            }
        }, '-', {
            text: '添加虚拟字段',
            iconCls: 'iconNew',
            handler: function () {
                addVirtualField();
            }
        }, '-', {
            text: '保存',
            iconCls: 'iconSave',
            handler: function () {
                saveGrid();
            }
        }, '-', {
            text: '删除',
            iconCls: 'iconDelete',
            id: "deleteC",
            // disabled : true,
            handler: function () {
                remove();
            }
        }, '-', {
            text: '刷新',
            tooltip: '刷新',
            handler: function () {
                store.reload();
            },
            iconCls: 'iconRefresh'
        }, '-', {
            text: '重新排序',
            tooltip: '重新排序',
            handler: function () {
                Ext.Ajax.request({
                    url: basePath + 'repository/worklist/columns/afreshSortFormMetadataMap',
                    method: 'POST',
                    params: {
                    	id:id
                    },
                    failure: function (response, options) {
                        Ext.MessageBox.alert('操作失败', '操作失败！可能是网络超时！');
                        return false;
                    },
                    success: function (response, options) {
                        if (response.responseText == 'ok') {
                            Ext.MessageBox.alert('提示', " 重新排序成功! ");
                            store.reload();
                        } else {
                            Ext.MessageBox.alert('提示', " 重新排序失败!! ");
                            return false;
                        }
                    }
                });
            },
            iconCls: 'iconRefresh'
        },'->']
    });
    viewport = new Ext.Viewport({
        layout: 'border',
        items: [grid]
    });
    store.load();
    var currentRowInd;
    var currentColInd;
    grid.addListener('cellmousedown', handleGridMove);
    function handleGridMove(o, r, c) {
        currentRowInd = r;
        currentColInd = c;
        return;
    }

    var ddrow = new Ext.dd.DropTarget(grid.container, {
        ddGroup: 'GridDD',
        copy: false,
        notifyDrop: function (dd, e, data) {
            var rows = data.selections;
            //data.rowIndex
            //var index = dd.getDragData(e).rowIndex;
            if (dd.getDragData(e).rowIndex == undefined) {
                return;
            }
            var sourceId = rows[0].id;
            var targetId = dd.getDragData(e).selections[0].id;
            handleSave(sourceId, targetId);
            return;
        }
    });
    // grid.addListener('afteredit', function(grid,record ,field ,value
    // ,originalValue ,row ) {
    // alert(value+row);
    // });
	/*grid.on('cellcontextmenu',function(grid,rowIndex,cellIndex,e){
		e.preventDefault();
		if(cellIndex==3){
			var record = grid.getStore().getAt(rowIndex);
			var value = '';
			if(cellIndex==3)value=record.get('columnName');
			
			var menus = new Ext.menu.Menu([{
					xtype:"button",text:"复制到剪贴板",pressed:true,
					handler:function(e){
						copy_clip(value);
					}
				}
			]);
			menus.showAt(e.getPoint());
		}
	});*/

});
function copy_clip(txt){ 
	 if(window.clipboardData) { 
            window.clipboardData.clearData(); 
            window.clipboardData.setData("Text", txt); 
    } else if(navigator.userAgent.indexOf("Opera") != -1) { 
         window.location = txt; 
    } else if (window.netscape) { 
         try { 
              netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); 
         } catch (e) { 
              alert("被浏览器拒绝！\n请在浏览器地址栏输入'about:config'并回车\n然后将'signed.applets.codebase_principal_support'设置为'true'"); 
         } 
         var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard); 
         if (!clip) 
              return; 
         var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable); 
         if (!trans) 
              return; 
         trans.addDataFlavor('text/unicode'); 
         var str = new Object(); 
         var len = new Object(); 
         var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString); 
         var copytext = txt; 
         str.data = copytext; 
         trans.setTransferData("text/unicode",str,copytext.length*2); 
         var clipid = Components.interfaces.nsIClipboard; 
         if (!clip) 
              return false; 
         clip.setData(trans,null,clipid.kGlobalClipboard); 
    } 
}
function addVirtualField() {
    var datasetUrl = basePath
        + 'repository/worklist/columns/getWorkListVirtualColumnsPage?id='
        + id;
    openSimpleExtWindow('添加虚拟字段', 500, 270, datasetUrl);
    if (activeDialog) {
        activeDialog.purgeListeners();
        activeDialog.addListener('show', handleShow);
        activeDialog.addListener('beforehide', handleHide);
        activeDialog.show();
    }

}
function saveGrid() {
    var m = store.getModifiedRecords();
    if (m.length > 0) {
        for (var i = 0, len = m.length; i < len; i++) {
            var rec = m[i];
        }
        var temp = 0;
        var json = [];
        Ext.each(m, function (item) {
            json.push(item.data);
        });
        store.commitChanges();
        Ext.Ajax.request({
            url: basePath + 'repository/worklist/columns/saveWorkListColumn',
            method: 'POST',
            params: {
                datas: Ext.util.JSON.encode(json),
                id: id
            },
            failure: function (response, options) {
                Ext.MessageBox.alert('操作失败', '操作失败！可能是网络超时！');
                return false;
            },
            success: function (response, options) {
                if (response.responseText == '1') {
                    Ext.MessageBox.alert('提示', " 保 存 成 功! ");
                    store.reload();
                } else if (response.responseText == '-1') {
                    Ext.MessageBox.alert('提示', " 保 存 失 败! ");
                    return false;
                }
            }
        });

    } else {
        Ext.MessageBox.alert('提示', '当前没有需要保存的记录!');
        return false;
    }
}

function remove() {
    var selectedKeys = grid.selModel.selections.keys;
    Ext.MessageBox.confirm('提示', '确定删除选定的字段?', function (btn) {
        if (btn == 'yes') {
            Ext.Ajax.request({
                url: basePath
                + 'repository/worklist/columns/removeWorkListColumn',
                method: 'POST',
                params: {
                    ids: selectedKeys,
                    id: id
                },
                failure: function (response, options) {
                    Ext.MessageBox.alert('操作失败', '操作失败！可能是网络超时！');
                    return false;
                },
                success: function (response, options) {
                    if (response.responseText == 'ok') {
                        store.commitChanges();
                        store.reload();
                        Ext.MessageBox.alert('提示', " 删 除 成 功! ");
                    }
                }
            });
        }

    });
}

function openWorkListMetadatMapWin() {
    var datasetUrl = basePath
        + 'repository/worklist/columns/openWorkListMetadataMapSelectPage?id='
        + id;
    openExtWindow(name, 750, 380, false, false, datasetUrl);
    var btnOk = new Ext.Button({
        text: '确定',
        tooltip: '添加到数据集',
        handler: function () {
            var selectJson = Operate_DlgPage.getSelectVavlue();
            Ext.Ajax.request({
                url: basePath
                + 'repository/worklist/columns/addWorkListMetadataMap',
                method: 'POST',
                params: {
                    id: id,
                    selectJson: selectJson
                },
                failure: function (response, options) {
                    Ext.MessageBox.alert('操作失败', '操作失败！可能是网络超时！');
                    return false;
                },
                success: function (response, options) {
                    // TODO 刷新右侧表格
                    OperateWinObj.hide();
                    store.reload();

                }
            });
        },
        minWidth: 75
    });
    OperateWinObj.addButton(btnOk);
    OperateWinObj.addButton({
        text: '关 闭',
        tooltip: '关闭向导',
        handler: function () {
            OperateWinObj.hide();
        },
        minWidth: 75
    });
    OperateWinObj.show();
}

function reflashGrid() {
    store.reload();
}

function renderer_hotLink(value, cell, record, rowIndex, columnIndex, store) {
    var clolumnId = record.data.id;
    var hotLinkName = record.data.hotlinkName;
    var hotlinkParam = record.data.hotlinkParam;
    hotLinkName = typeof (hotLinkName) == "undefined" || hotLinkName == '无' ? "设置"
        : hotLinkName;
    hotlinkParam = typeof (hotlinkParam) == "undefined" || hotlinkParam == '' ? ""
        : hotlinkParam;
    var val = '<a id="' + clolumnId
        + '" href=\'javascript:void(0)\' onclick="showSetWin(\''
        + clolumnId + '\',\'' + hotLinkName + '\',\'' + rowIndex + '\',\''
        + hotLinkName + '\')">' + hotLinkName + '</a>';
    return val;
}

function handleSave(sourceId, targetId) {
    Ext.getBody().mask("保存排序...");
    Ext.Ajax.request({
        url: basePath + 'repository/worklist/columns/sortGird',
        method: 'POST',
        params: {
            sourceId: sourceId,
            targetId: targetId,
            id: id
        },
        failure: function (response, options) {
            Ext.MessageBox.alert('操作失败', '操作失败！可能是网络超时！');
            return false;
        },
        success: function (response, options) {
            Ext.getBody().unmask();
            if (response.responseText != '1') {
                Ext.MessageBox.alert('提示', " 排序发生错误，请刷新重新重试! ");
            } else {
                store.load();
            }
        }
    });
}
Ext.util.Format.comboRenderer = function (combo) {
    return function (value) {
        var record = combo.findRecord(combo.valueField, value);
        return record ? record.get(combo.displayField) : combo.valueNotFoundText;
    }
}


function renderer_data(value, cell, record, rowIndex, columnIndex, store) {

    var ref_type = record.data.ref_type;
    var ref_params = record.data.ref_params;
    var ref_type_title = ref_type == null || ref_type == '' ? '--' : ref_type;
    var val = '<a href=\'javascript:void(0)\' onclick="openDataRefDesignDialog(\'' + ref_type + '\',\'' + ref_params + '\');">' + ref_type_title + '</a>';
    return val;
}

function tableReload() {
    store.reload();
}